<?php
class App_Admin_Model_Plugin extends Main_Db_Table_Abstract
{
	/**
	 * @var string
	 */
	protected $_name = 'plugin';
	
	/**
	 * @var string
	 */
	protected $_primary = 'id';
	
	/**
	 * @var array
	 */
	protected $_fields = array(
		'id',
	    'name',
		'f_active',  
	);
	
	/**
	 * 
	 * @var App_Admin_Model_PluginI18n
	 */
	protected $_modelPluginI18n;	
	
	/**
	 * @return void
	 */
	public function init() 
	{
		$this->_modelPluginI18n = Main_Model::factory('Admin_Model_PluginI18n');
	}

	/**
	 * @param array $data
	 * @return bool
	 */
	public function insertItem($data) 
	{
		$dataOk = $this->beforeSave($data, array(
			'name', 'f_active'  
		), array(
			'name',
		));
		
		$result = $this->insert($dataOk);
				
		$data['plugin_id'] = $this->lastInsertId(); 
		$res1 = $this->_modelPluginI18n->insertItem($data);
		
		return $result && $res1;
	}
	
	/**
	 * @param array $data
	 * @param int $id
	 * @return bool
	 */
	public function updateItem($data, $id)
	{
		$id = $this->escape($id);
		$dataOk = $this->beforeSave($data, array(
			'name', 'f_active' 
		), array(
			'name',
		));
    	
		$res1 = $this->_modelPluginI18n->updateItem($data, $id);  	
		$res2 = $this->update($dataOk, "id={$id}"); 
		
    	return $res1 && $res2;
	}
	
	/**
	 * @param int $id
	 * @param int $langId
	 * @return array
	 */
	public function getItemById($id, $langId) 
	{
		$id = $this->escape($id);
		
		$sql = "
			SELECT 
				p.id
				, p.name
				, p.f_active
				, p_i18n.title
				, p_i18n.description
			FROM
				plugin p
			INNER JOIN
				plugin_i18n p_i18n
				ON
					(p.id=p_i18n.plugin_id AND p_i18n.lang_id={$langId})		
			WHERE
				p.id={$id}		
		";
				
		$list = $this->getAdapter()->fetchRow($sql);

		return $list;
	}
	
	/**
	 * @param int $langId
	 * @return array
	 */
	public function getAll($langId) 
	{
		$langId = $this->escape($langId);
		
		$sql = "
			SELECT 
				p.id
				, p.name
				, p.f_active
				, p_i18n.title
				, p_i18n.description
			FROM
				plugin p
			INNER JOIN
				plugin_i18n p_i18n
				ON
					(p.id=p_i18n.plugin_id AND p_i18n.lang_id={$langId})		
		";
				
		$list = $this->getAdapter()->fetchAll($sql);

		return $list;
	}
	
	
	/**
	 * @param int $id
	 * @return bool
	 */
	public function deleteItem($id) 
	{
		$id = $this->escape($id);
		if ($this->_modelPluginI18n->deleteItemByPluginId($id)) {
			return $this->delete("id={$id}");
		} else {
			return false;
		}	
	}
	
} 
